|
Implementation by Delegation
|
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main() {
val b = BaseImpl(10)
Derived(b).print()
}
|
protocol Base {
func print()
}
class BaseImpl: Base {
private var x = 0
init(x: Int) {
self.x = x
}
func print() { Swift.print(x) }
}
class Derived: Base {
private var b: Base
init(_ b: Base) {
self.b = b
}
func print() {
b.print()
}
}
let b = BaseImpl(x: 10)
Derived(b).print()
|
Overriding a member of an interface implemented by delegation
|
interface Base {
fun printMessage()
fun printMessageLine()
}
class BaseImpl(val x: Int) : Base {
override fun printMessage() { print(x) }
override fun printMessageLine() { println(x) }
}
class Derived(b: Base) : Base by b {
override fun printMessage() { print("abc") }
}
fun main() {
val b = BaseImpl(10)
Derived(b).printMessage()
Derived(b).printMessageLine()
}
|
protocol Base {
func printMessage()
func printMessageLine()
}
class BaseImpl: Base {
private var x = 0
init(x: Int) {
self.x = x
}
func printMessage() { print(x) }
func printMessageLine() { print(x) }
}
class Derived: Base {
private var b: Base
init(_ b: Base) {
self.b = b
}
func printMessage() { b.printMessage() }
func printMessageLine() { print("abc") }
}
let b = BaseImpl(x: 10)
Derived(b).printMessage()
Derived(b).printMessageLine()
|
interface Base {
val message: String
fun print()
}
class BaseImpl(val x: Int) : Base {
override val message = "BaseImpl: x = $x"
override fun print() { println(message) }
}
class Derived(b: Base) : Base by b {
// This property is not accessed from b's implementation of `print`
override val message = "Message of Derived"
}
fun main() {
val b = BaseImpl(10)
val derived = Derived(b)
derived.print()
println(derived.message)
}
|
protocol Base {
var message: String { get }
func print()
}
class BaseImpl: Base {
private var x = 0
init(x: Int) {
self.x = x
}
var message: String {
get { "BaseImpl: x = \(x)" }
}
func print() { Swift.print(message) }
}
class Derived: Base {
private var b: Base
init(_ b: Base) {
self.b = b
}
let message = "Message of Derived"
func print() { b.print() }
}
let b = BaseImpl(x: 10)
let derived = Derived(b)
derived.print()
print(derived.message)
|